/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/
package com.feiyue;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.feiyue.basic.server.cache.CacheFetch;
import com.feiyue.basic.server.cache.DiskLruCache;
import com.feiyue.basic.server.db.BookCollectDBHandler;
import com.feiyue.basic.server.net.NovelInfo;
import com.feiyue.basic.server.parser.Book;
import com.feiyue.helper.BookShelfAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BookShelfActivity extends Activity {
	public static final String BOOKID = "bookid";
	public static final String MESSAGERECEIVER = "MESSAGERECEIVER_BOOKID";
	public static boolean isupdaterunning = false;
	private List<Book> booklist;
	private LinearLayout bookshelf_holder;
	private LinearLayout bookshelf_simulate_linearLayout;
	private PullToRefreshScrollView bookshelf_simulate_scrollview;
	private Context context;
	protected CharSequence firstlabel = "更新书架中的所有小说";
	private Handler handler;
	private double height;
	private boolean issimulate = true;
	private PullToRefreshListView listView;
	private MessageReceiver messageReceiver;
	private ImageView mode_switch_image;
	private LinearLayout modeswitch;
	protected CharSequence secondlabel = "松开立即更新、往回拉则取消";
	protected CharSequence thirdlabel = "正在更新";
	private double width;

	//TODO 待检查
	private void handlerow(LinearLayout linearlayout, int i, int j)
    {
//        int localindex = j * 3;
//        
//        while (localindex < 3 * (j + 1)) {
//        	if (localindex >= i) {
//        		if (localindex % 3 == 0)
//                    ((ImageView)linearlayout.findViewById(0x7f060089)).setImageBitmap(null);
//                else
//                if (localindex % 3 == 1)
//                    ((ImageView)linearlayout.findViewById(0x7f06008a)).setImageBitmap(null);
//                else
//                if (localindex % 3 == 2)
//                    ((ImageView)linearlayout.findViewById(0x7f06008b)).setImageBitmap(null);
//        	} else {
//        		if (localindex % 3 == 0)
//                {
//                    ImageView imageview2 = (ImageView)linearlayout.findViewById(0x7f060089);
//                    setimageview(imageview2, localindex);
//                    imageview2.setBackgroundResource(0x7f02000e);
//                    imageview2.setOnClickListener(new android.view.View.OnClickListener() {
//
//                        public void onClick(View view)
//                        {
//                            start(localindex);
//                        }
//                    });
//                } else
//                if (localindex % 3 == 1)
//                {
//                    ImageView imageview1 = (ImageView)linearlayout.findViewById(0x7f06008a);
//                    setimageview(imageview1, localindex);
//                    imageview1.setBackgroundResource(0x7f02000e);
//                    imageview1.setOnClickListener(new android.view.View.OnClickListener() {
//
//                        public void onClick(View view)
//                        {
//                            start(localindex);
//                        }
//                    });
//                } else
//                if (localindex % 3 == 2)
//                {
//                    ImageView imageview = (ImageView)linearlayout.findViewById(0x7f06008b);
//                    setimageview(imageview, localindex);
//                    imageview.setBackgroundResource(0x7f02000e);
//                    imageview.setOnClickListener(new android.view.View.OnClickListener() {
//
//                        public void onClick(View view)
//                        {
//                            start(localindex);
//                        }
//                    });
//                }
//        	}
//        	
////        	localindex++;
//        }
    }

	private void setimageview(ImageView imageview, int i)
    {
        imageview.setBackgroundResource(((Book)booklist.get(i)).getCoverid(Boolean.valueOf(true)));
        if (((Book)booklist.get(i)).getCoverAddr() != null && !((Book)booklist.get(i)).getCoverAddr().equals("null")) {
        	File file1;
            Bitmap bitmap;
            File file = DiskLruCache.getDiskCacheDir(context, "http");
            DiskLruCache disklrucache = DiskLruCache.openCache_get(context, file, 0xa00000L);
            file1 = new File(disklrucache.createFilePath(((Book)booklist.get(i)).getCoverAddr()));
            if (!disklrucache.containsKey(((Book)booklist.get(i)).getCoverAddr())) {
            	Myrunnable myrunnable = new Myrunnable(imageview);
                Handler handler1 = new Handler();
                (new MyThread(context, myrunnable, handler1, ((Book)booklist.get(i)).getCoverAddr())).start();
            } else {
            	try {
            		bitmap = null;
                    Bitmap bitmap1 = BitmapFactory.decodeFile(file1.getPath());
                    bitmap = bitmap1;
                    if (bitmap != null)
                    {
                        int j = bitmap.getWidth();
                        int k = bitmap.getHeight();
                        float f = (float)(width / (double)j);
                        float f1 = (float)(height / (double)k);
                        Matrix matrix = new Matrix();
                        matrix.postScale(f, f1);
                        imageview.setImageBitmap(Bitmap.createBitmap(bitmap, 0, 0, j, k, matrix, true));
                    }
            	} catch (OutOfMemoryError e) {
            		System.gc();
            	}
            }
        }
    }

	private void showlistview()
    {
        LayoutInflater layoutinflater;
        android.view.ViewGroup.LayoutParams layoutparams;
        int i;
        ArrayList arraylist;
        int j;
        HashMap hashmap;
        String as[];
        int ai[];
        BookShelfAdapter bookshelfadapter;
        try
        {
            BookCollectDBHandler bookcollectdbhandler = new BookCollectDBHandler(context);
            booklist = bookcollectdbhandler.getBookList(context);
            bookcollectdbhandler.destroy();
        }
        catch (Exception exception) { }
        mode_switch_image.setImageResource(R.drawable.mode_simulate);
        layoutinflater = (LayoutInflater)context.getSystemService("layout_inflater");
        bookshelf_holder.removeAllViews();
        listView = (PullToRefreshListView)layoutinflater.inflate(R.layout.bookshelf_list, null);
        layoutparams = new android.view.ViewGroup.LayoutParams(-1, -1);
        bookshelf_holder.addView(listView, layoutparams);
        issimulate = false;
        listView.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.BOTH);
        listView.setAnimation(null);
        listView.getLoadingLayoutProxy().setPullLabel(firstlabel);
        listView.getLoadingLayoutProxy().setRefreshingLabel(thirdlabel);
        listView.getLoadingLayoutProxy().setReleaseLabel(secondlabel);
        //TODO 是否自己加的？
//        listView.getLoadingLayoutProxy().setTextColor(0xff000000);
        i = 0;
        if (booklist != null)
            i = booklist.size();
        arraylist = new ArrayList();
        j = 0;
        
        while (j < i) {
        	hashmap = new HashMap();
            hashmap.put("ItemTile", ((Book)booklist.get(j)).getName());
            hashmap.put("ItemAuthor", (new StringBuilder("作者:")).append(((Book)booklist.get(j)).getAuthor()).toString());
            hashmap.put("ItemIntroduction", (new StringBuilder("介绍:")).append(((Book)booklist.get(j)).getIntroduction()).toString());
            arraylist.add(hashmap);
            j++;
        }
        
        as = new String[3];
        as[0] = "ItemTile";
        as[1] = "ItemAuthor";
        as[2] = "ItemIntroduction";
        ai = new int[3];
        ai[0] = 0x7f06002f;
        ai[1] = 0x7f060030;
        ai[2] = 0x7f060031;
        bookshelfadapter = new BookShelfAdapter(this, arraylist, 0x7f030003, as, ai, booklist);
        listView.setOnRefreshListener(new com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener() {

            public void onRefresh(PullToRefreshBase pulltorefreshbase)
            {
                String s = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(), 0x80011);
                pulltorefreshbase.getLoadingLayoutProxy().setLastUpdatedLabel(s);
                (new GetDataTask(true)).execute(new Void[0]);
            }
        });
        listView.setAdapter(bookshelfadapter);
        listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView adapterview, View view, int k, long l)
            {
                int i1 = k - 1;
                start(i1);
            }
        });
    }

	public void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        setContentView(R.layout.bookshelf);
        context = getApplicationContext();
        handler = new Handler();
        messageReceiver = new MessageReceiver();
        IntentFilter intentfilter = new IntentFilter("MESSAGERECEIVER_BOOKID");
        registerReceiver(messageReceiver, intentfilter);
        bookshelf_holder = (LinearLayout)findViewById(R.id.holder);
        mode_switch_image = (ImageView)findViewById(R.id.mode_switch_image);
        width = BitmapFactory.decodeResource(context.getResources(), R.drawable.big_cover1).getWidth();
        height = BitmapFactory.decodeResource(context.getResources(), R.drawable.big_cover1).getHeight();
        if (issimulate)
            showsimulateview();
        else
            showlistview();
        modeswitch = (LinearLayout)findViewById(R.id.mode_switch);
        modeswitch.setOnClickListener(new android.view.View.OnClickListener() {

            public void onClick(View view)
            {
                if (issimulate)
                    showlistview();
                else
                    showsimulateview();
            }
        });
    }

	protected void onDestroy() {
		unregisterReceiver(this.messageReceiver);
		super.onDestroy();
	}

	protected void onResume() {
		super.onResume();
	}

	protected void showsimulateview()
    {
        LayoutInflater layoutinflater;
        android.view.ViewGroup.LayoutParams layoutparams;
        int i;
        int j;
        int k;
        LinearLayout linearlayout;
        LinearLayout linearlayout1;
        LinearLayout linearlayout2;
        LinearLayout linearlayout3;
        try
        {
            BookCollectDBHandler bookcollectdbhandler = new BookCollectDBHandler(context);
            booklist = bookcollectdbhandler.getBookList(context);
            bookcollectdbhandler.destroy();
        }
        catch (Exception exception) { }
        mode_switch_image.setImageResource(0x7f020052);
        layoutinflater = (LayoutInflater)context.getSystemService("layout_inflater");
        bookshelf_simulate_scrollview = (PullToRefreshScrollView)layoutinflater.inflate(0x7f030008, null);
        bookshelf_simulate_linearLayout = (LinearLayout)bookshelf_simulate_scrollview.findViewById(0x7f060088);
        issimulate = true;
        bookshelf_holder.removeAllViews();
        layoutparams = new android.view.ViewGroup.LayoutParams(-1, -1);
        bookshelf_holder.addView(bookshelf_simulate_scrollview, layoutparams);
        bookshelf_simulate_scrollview.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.BOTH);
        bookshelf_simulate_scrollview.setAnimation(null);
        bookshelf_simulate_scrollview.getLoadingLayoutProxy().setPullLabel(firstlabel);
        bookshelf_simulate_scrollview.getLoadingLayoutProxy().setRefreshingLabel(thirdlabel);
        bookshelf_simulate_scrollview.getLoadingLayoutProxy().setReleaseLabel(secondlabel);
//        bookshelf_simulate_scrollview.getLoadingLayoutProxy().setTextColor(0xff000000);
        i = 0;
        if (booklist != null)
            i = booklist.size();
        if (i != 0) {
        	j = i / 3;
            if (i % 3 > 0)
                j++;
            k = 0;
            
            while (k < j) {
            	if (k == 0)
                {
                    linearlayout1 = (LinearLayout)layoutinflater.inflate(0x7f030009, null);
                    bookshelf_simulate_linearLayout.addView(linearlayout1);
                    handlerow(linearlayout1, i, k);
                } else
                if (k != j)
                {
                    linearlayout = (LinearLayout)layoutinflater.inflate(0x7f03000b, null);
                    bookshelf_simulate_linearLayout.addView(linearlayout);
                    handlerow(linearlayout, i, k);
                }
                k++;
            }
            
            linearlayout2 = (LinearLayout)layoutinflater.inflate(0x7f03000c, null);
            bookshelf_simulate_linearLayout.addView(linearlayout2);
            bookshelf_simulate_scrollview.setOnRefreshListener(new com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener() {

                public void onRefresh(PullToRefreshBase pulltorefreshbase)
                {
                    String s = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(), 0x80011);
                    pulltorefreshbase.getLoadingLayoutProxy().setLastUpdatedLabel(s);
                    (new GetDataTask(false)).execute(new Void[0]);
                }
            });
        } else {
        	linearlayout3 = (LinearLayout)layoutinflater.inflate(0x7f03000a, null);
            bookshelf_simulate_linearLayout.addView(linearlayout3);
        }
    }

	protected void start(int paramInt) {
		String str1 = ((Book) this.booklist.get(paramInt)).getName();
		int i = ((Book) this.booklist.get(paramInt)).getId();
		int j = ((Book) this.booklist.get(paramInt)).getCoverid();
		String str2 = ((Book) this.booklist.get(paramInt)).getCoverAddr();
		int k = ((Book) this.booklist.get(paramInt)).getdlstate();
		String str3 = ((Book) this.booklist.get(paramInt)).getAuthor();
		String str4 = ((Book) this.booklist.get(paramInt)).getIntroduction();
		String str5 = ((Book) this.booklist.get(paramInt)).getIssuestate();
		//TODO
//		Intent localIntent = new Intent(getApplicationContext(),
//				BookBriefActivity.class);
//		localIntent.putExtra("categoryname", "");
//		localIntent.putExtra("categoryid",
//				((Book) this.booklist.get(paramInt)).getCategoryId());
//		localIntent.putExtra("bookname", str1);
//		localIntent.putExtra("bookid", i);
//		localIntent.putExtra("author", str3);
//		localIntent.putExtra("introduction", str4);
//		localIntent.putExtra("issuestate", str5);
//		localIntent.putExtra("coverid", j);
//		localIntent.putExtra("coverAddr", str2);
//		localIntent.putExtra("dlstate", k);
//		startActivity(localIntent);
//		overridePendingTransition(2130968587, 0);
	}

	public void update()
    {
        List list;
        int i;
        int j;
        isupdaterunning = true;
        list = booklist;
        i = list.size();
        j = 0;
        
        while (j < i) {
        	int k = ((Book)list.get(j)).getId();
            String s = NovelInfo.getUrl2Chapterlist(k);
            int l = ((Book)list.get(j)).getCategoryId();
            ((Book)list.get(j)).getIssuestate();
            NovelInfo.getChapterList(context, s, l, k, "update", null);
            Intent intent = new Intent("CatologUpdate");
            intent.putExtra("BookID", (new StringBuilder(String.valueOf(k))).toString());
            context.sendBroadcast(intent);
            j++;
        }
        
        isupdaterunning = false;
    }

	private class GetDataTask extends AsyncTask
    {

        private boolean dotips;
        private boolean isListView;

        protected Object doInBackground(Object aobj[])
        {
            return doInBackground((Void[])aobj);
        }

        protected String[] doInBackground(Void avoid[])
        {
            if (!BookShelfActivity.isupdaterunning)
            {
                update();
                dotips = true;
            } else
            {
                while (BookShelfActivity.isupdaterunning) 
                    try
                    {
                        Thread.sleep(2000L);
                    }
                    catch (InterruptedException interruptedexception) { }
            }
            return null;
        }

        protected void onPostExecute(Object obj)
        {
            onPostExecute((String[])obj);
        }

        protected void onPostExecute(String as[])
        {
            if (dotips)
                Toast.makeText(context, "收藏中的小说已完成更新", 1).show();
            if (isListView)
                listView.onRefreshComplete();
            else
                bookshelf_simulate_scrollview.onRefreshComplete();
            super.onPostExecute(as);
        }

        public GetDataTask(boolean flag)
        {
            super();
            dotips = false;
            isListView = flag;
        }
    }

	public class MessageReceiver extends BroadcastReceiver {
		public void onReceive(Context paramContext, Intent paramIntent) {
			if (!(BookShelfActivity.this.issimulate)) {
				BookShelfActivity.this.showlistview();
			} else {
			    BookShelfActivity.this.showsimulateview();
			}
		}
	}

	public class MyThread extends Thread
    {

        private Context context;
        private String coverAddress;
        private Handler handler;
        private Myrunnable myrunnable;

        public void run()
        {
            File file = CacheFetch.getFile(context, coverAddress, coverAddress, false);
            if (file != null) {
            	try {
            		Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                    
                    if (bitmap != null)
                    {
                        int i = bitmap.getWidth();
                        int j = bitmap.getHeight();
                        float f = (float)(width / (double)i);
                        float f1 = (float)(height / (double)j);
                        Matrix matrix = new Matrix();
                        matrix.postScale(f, f1);
                        Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, i, j, matrix, true);
                        myrunnable.setBitmap(bitmap1);
                        handler.post(myrunnable);
                    }
            	} catch (OutOfMemoryError e) {
            		System.gc();
            	}
                
            }
        }

        public MyThread(Context context1, Myrunnable myrunnable1, Handler handler1, String s)
        {
            super();
            context = context1;
            myrunnable = myrunnable1;
            handler = handler1;
            coverAddress = s;
        }
    }

	public class Myrunnable implements Runnable {
		private Bitmap bitmap = null;
		private ImageView coverImageView = null;

		public Myrunnable(ImageView paramImageView) {
			this.coverImageView = paramImageView;
		}

		public void run() {
			this.coverImageView.setImageBitmap(this.bitmap);
		}

		public void setBitmap(Bitmap paramBitmap) {
			this.bitmap = paramBitmap;
		}
	}
}